﻿using Modbus.Device;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.LinkLabel;

namespace DeltaPlcSystem
{
    public partial class PlcControl : UserControl
    {
        public PlcControl(DeviceClass dc)
        {
            InitializeComponent();
            uiLabel23.ForeColor=Color.White;
            uiRichTextBox1.ReadOnly = true;
            Txt_Server.Text = Form1.PQMserverURL;
            Txt_Server.ReadOnly = true;


            Txt_client_IP.Text = dc.Ip;
            Txt_client_IP.ReadOnly = true;

            Txt_interfaceID.Text = dc.InterfaceID;
            Txt_interfaceID.ReadOnly = true;

            Txt_equipType.Text = dc.EquipType;
            Txt_equipType.ReadOnly = true;

            Txt_status.Text = dc.Status;
            Txt_status.ReadOnly = true;

            Txt_statusCode.Text = dc.StatusCode;
            Txt_statusCode.ReadOnly = true;

            Txt_passQty.Text = dc.PassQty;
            Txt_passQty.ReadOnly = true;

            Txt_failQty.Text = dc.FailQty;
            Txt_failQty.ReadOnly = true;

            Txt_errorCnt.Text = dc.ErrorCnt;
            Txt_errorCnt.ReadOnly = true;

            Txt_errorTimes.Text = dc.ErrorTimes;
            Txt_errorTimes.ReadOnly = true;

            Txt_cycleTime.Text = dc.CycleTime;
            Txt_cycleTime.ReadOnly = true;

            Txt_runningTime.Text = dc.RunningTime;
            Txt_runningTime.ReadOnly = true;

            Txt_waitingTime.Text = dc.WaitingTime;
            Txt_waitingTime.ReadOnly = true;

            Txt_selfCheck.Text = dc.SelfCheck;
            Txt_selfCheck.ReadOnly = true;

            Txt_inputQty.Text = dc.InputQty;
            Txt_inputQty.ReadOnly = true;

            Txt_barcode.Text = dc.Barcode;
            Txt_barcode.ReadOnly = true;

            Txt_model.Text = dc.Model;
            Txt_model.ReadOnly = true;

            Txt_CT_Q.Text = dc.CT_Q;
            Txt_CT_Q.ReadOnly = true;

            Txt_CT_M.Text = dc.CT_M;
            Txt_CT_M.ReadOnly = true;

            uiTextBox23.ReadOnly = true;

            uiTextBox22.Text = Form1.UpTime.ToString();
            uiTextBox22.ReadOnly = true;

            uiTextBox3.Text=dc.ModulusValue.ToString();
            uiTextBox3.ReadOnly = true;

            uiTextBox1.ReadOnly = true;
            uiTextBox1.Text = dc.EquipName;
            uiTextBox2.ReadOnly = true;

            if (dc.IsEnable == "1")
            {
                uiLabel23.BackColor = Color.Black;
                uiLabel23.Text = "设备启用，通讯未连接";
            }
            else
            {
                uiLabel23.BackColor = Color.Gray;
                uiLabel23.Text = "设备未启用";
            }



            if (dc.PlcMode == "0")
            {
                uiTextBox23.Text = "AsAh-Series";
            }
            else if (dc.PlcMode == "1")
            { 
                uiTextBox23.Text = "Dvp-Series";
            }
            else if (dc.PlcMode == "2")
            {
                uiTextBox23.Text = "HMI";
            }


            uiLabel28.Text = dc.VirtualMachine;


            uiLabel29.Text = "state " + dc.TbsState + "-" + dc.TbsCount;


            if (dc.IsTimeEnable)
            {
                uiLabel30.Text = "已启动定时";
            }
            else 
            {
                uiLabel30.Text = "";
            }
        }


        public void ReadPlcThread(object tempDevices)
        {
            DeviceClass tempDevice = (DeviceClass)tempDevices;
            while (tempDevice.IsThreadControl)
            {
                if (tempDevice.IsReadData)
                {
                    try
                    {
                        tempDevice.LogStr.Clear();
                        tempDevice.LogStr.Append(PublicClass.NetLog(0, "开始") + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                    }
                    catch { }

                    PingReply replyTemp = null;

                    try
                    {                     
                        replyTemp = tempDevice.PlcModbus.ping.Send(tempDevice.Ip, 500);
                    }
                    catch (Exception ex)
                    {
                        uiLabel23.Invoke((MethodInvoker)delegate () {
                            uiLabel23.BackColor = Color.Red;
                            uiLabel23.Text = "PING地址异常";
                        });
                        replyTemp = null;
                        tempDevice.LogStr.Append("\r\n"+PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                    }

                    try
                    {
                        if (replyTemp != null)
                        {
                            if (replyTemp.Status == IPStatus.Success)
                            {
                                if (tempDevice.IsConnected)
                                {
                                    string statuT = string.Empty;
                                    string statusCodeT = string.Empty;
                                    string passT = string.Empty;
                                    string failT = string.Empty;
                                    string errorCntT = string.Empty;
                                    string errorTimeT = string.Empty;
                                    string cycleTimeT = string.Empty;
                                    string runningTimeT = string.Empty;
                                    string waitingTimeT = string.Empty;
                                    string selfCheckT = string.Empty;
                                    string inputQtyT = string.Empty;
                                    string barcodeT = string.Empty;
                                    string modelT = string.Empty;
                                    string ctqT = string.Empty;
                                    string ctmT = string.Empty;
                                    try
                                    {
                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(2, "开始读取PLC数据") + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                        if (tempDevice.PlcMode == "1")//DVP-PLC
                                        {
                                            statuT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44762, 1)[0].ToString();
                                            Txt_status.Invoke((MethodInvoker)delegate () { Txt_status.Text = statuT; });

                                            statusCodeT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44760, 1)[0].ToString();
                                            Txt_statusCode.Invoke((MethodInvoker)delegate () { Txt_statusCode.Text = statusCodeT; });


                                            ushort[] ushortPass = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44758, 2);
                                            string tempPassQ = PublicClass.ToBinary(ushortPass[1]) + PublicClass.ToBinary(ushortPass[0]);
                                            passT = Convert.ToInt64(tempPassQ, 2).ToString();
                                            Txt_passQty.Invoke((MethodInvoker)delegate () { Txt_passQty.Text = passT; });

                                            ushort[] ushortFail = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44756, 2);
                                            string tempFailQ = PublicClass.ToBinary(ushortFail[1]) + PublicClass.ToBinary(ushortFail[0]);
                                            failT = Convert.ToInt64(tempFailQ, 2).ToString();
                                            Txt_failQty.Invoke((MethodInvoker)delegate () { Txt_failQty.Text = failT; });

                                            errorCntT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44754, 1)[0].ToString();
                                            Txt_errorCnt.Invoke((MethodInvoker)delegate () { Txt_errorCnt.Text = errorCntT; });


                                            ushort[] ushortErrorTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44752, 2);
                                            string tempErrorT = PublicClass.ToBinary(ushortErrorTimes[1]) + PublicClass.ToBinary(ushortErrorTimes[0]);
                                            errorTimeT = (Convert.ToInt64(tempErrorT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_errorTimes.Invoke((MethodInvoker)delegate () { Txt_errorTimes.Text = errorTimeT; });


                                            ushort[] ushortCycleTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44750, 2);
                                            string tempCycleT = PublicClass.ToBinary(ushortCycleTimes[1]) + PublicClass.ToBinary(ushortCycleTimes[0]);
                                            cycleTimeT = (Convert.ToInt64(tempCycleT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_cycleTime.Invoke((MethodInvoker)delegate () { Txt_cycleTime.Text = cycleTimeT; });


                                            ushort[] ushortRunTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44748, 2);
                                            string tempRunT = PublicClass.ToBinary(ushortRunTimes[1]) + PublicClass.ToBinary(ushortRunTimes[0]);
                                            runningTimeT = (Convert.ToInt64(tempRunT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_runningTime.Invoke((MethodInvoker)delegate () { Txt_runningTime.Text = runningTimeT; });


                                            ushort[] ushortWaitTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44746, 2);
                                            string tempWaitT = PublicClass.ToBinary(ushortWaitTimes[1]) + PublicClass.ToBinary(ushortWaitTimes[0]);
                                            waitingTimeT = (Convert.ToInt64(tempWaitT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_waitingTime.Invoke((MethodInvoker)delegate () { Txt_waitingTime.Text = waitingTimeT; });


                                            selfCheckT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44744, 1)[0].ToString();
                                            Txt_selfCheck.Invoke((MethodInvoker)delegate () { Txt_selfCheck.Text = selfCheckT; });


                                            ushort[] ushortInput = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44742, 2);
                                            string tempInputQ = PublicClass.ToBinary(ushortInput[1]) + PublicClass.ToBinary(ushortInput[0]);
                                            inputQtyT = Convert.ToInt64(tempInputQ, 2).ToString();
                                            Txt_inputQty.Invoke((MethodInvoker)delegate () { Txt_inputQty.Text = inputQtyT; });

                                            barcodeT = "";
                                            Txt_barcode.Invoke((MethodInvoker)delegate () { Txt_barcode.Text = barcodeT; });

                                            modelT = "";
                                            Txt_model.Invoke((MethodInvoker)delegate () { Txt_model.Text = modelT; });

                                            ctqT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44728, 1)[0].ToString();
                                            Txt_CT_Q.Invoke((MethodInvoker)delegate () { Txt_CT_Q.Text = ctqT; });

                                            ctmT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, 44732, 1)[0].ToString();
                                            Txt_CT_M.Invoke((MethodInvoker)delegate () { Txt_CT_M.Text = ctmT; });


                                            uiLabel23.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiLabel23.BackColor = Color.Green;
                                                uiLabel23.Text = "数据读取成功";
                                            });

                                        }
                                        else//as-plc&HMI
                                        {
                                            statuT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.Status.Substring(1)), 1)[0].ToString();
                                            Txt_status.Invoke((MethodInvoker)delegate () { Txt_status.Text = statuT; });

                                            statusCodeT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.StatusCode.Substring(1)), 1)[0].ToString();
                                            Txt_statusCode.Invoke((MethodInvoker)delegate () { Txt_statusCode.Text = statusCodeT; });



                                            ushort[] ushortPass = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.PassQty.Substring(1)), 2);
                                            string tempPassQ = PublicClass.ToBinary(ushortPass[1]) + PublicClass.ToBinary(ushortPass[0]);
                                            passT = Convert.ToInt64(tempPassQ, 2).ToString();
                                            Txt_passQty.Invoke((MethodInvoker)delegate () { Txt_passQty.Text = passT; });


                                            ushort[] ushortFail = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.FailQty.Substring(1)), 2);
                                            string tempFailQ = PublicClass.ToBinary(ushortFail[1]) + PublicClass.ToBinary(ushortFail[0]);
                                            failT = Convert.ToInt64(tempFailQ, 2).ToString();
                                            Txt_failQty.Invoke((MethodInvoker)delegate () { Txt_failQty.Text = failT; });


                                            errorCntT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.ErrorCnt.Substring(1)), 1)[0].ToString();
                                            Txt_errorCnt.Invoke((MethodInvoker)delegate () { Txt_errorCnt.Text = errorCntT; });


                                            ushort[] ushortErrorTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.ErrorTimes.Substring(1)), 2);
                                            string tempErrorT = PublicClass.ToBinary(ushortErrorTimes[1]) + PublicClass.ToBinary(ushortErrorTimes[0]);
                                            errorTimeT = (Convert.ToInt64(tempErrorT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_errorTimes.Invoke((MethodInvoker)delegate () { Txt_errorTimes.Text = errorTimeT; });


                                            ushort[] ushortCycleTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.CycleTime.Substring(1)), 2);
                                            string tempCycleT = PublicClass.ToBinary(ushortCycleTimes[1]) + PublicClass.ToBinary(ushortCycleTimes[0]);
                                            cycleTimeT = (Convert.ToInt64(tempCycleT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_cycleTime.Invoke((MethodInvoker)delegate () { Txt_cycleTime.Text = cycleTimeT; });


                                            ushort[] ushortRunTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.RunningTime.Substring(1)), 2);
                                            string tempRunT = PublicClass.ToBinary(ushortRunTimes[1]) + PublicClass.ToBinary(ushortRunTimes[0]);
                                            runningTimeT = (Convert.ToInt64(tempRunT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_runningTime.Invoke((MethodInvoker)delegate () { Txt_runningTime.Text = runningTimeT; });


                                            ushort[] ushortWaitTimes = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.WaitingTime.Substring(1)), 2);
                                            string tempWaitT = PublicClass.ToBinary(ushortWaitTimes[1]) + PublicClass.ToBinary(ushortWaitTimes[0]);
                                            waitingTimeT = (Convert.ToInt64(tempWaitT, 2) / tempDevice.ModulusValue).ToString();
                                            Txt_waitingTime.Invoke((MethodInvoker)delegate () { Txt_waitingTime.Text = waitingTimeT; });

                                            selfCheckT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.SelfCheck.Substring(1)), 1)[0].ToString();
                                            Txt_selfCheck.Invoke((MethodInvoker)delegate () { Txt_selfCheck.Text = selfCheckT; });

                                            ushort[] ushortInput = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.InputQty.Substring(1)), 2);
                                            string tempInputQ = PublicClass.ToBinary(ushortInput[1]) + PublicClass.ToBinary(ushortInput[0]);
                                            inputQtyT = Convert.ToInt64(tempInputQ, 2).ToString();
                                            Txt_inputQty.Invoke((MethodInvoker)delegate () { Txt_inputQty.Text = inputQtyT; });

                                            barcodeT = "";
                                            Txt_barcode.Invoke((MethodInvoker)delegate () { Txt_barcode.Text = barcodeT; });

                                            modelT = "";
                                            Txt_model.Invoke((MethodInvoker)delegate () { Txt_model.Text = modelT; });

                                            ctqT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.CT_Q.Substring(1)), 1)[0].ToString();
                                            Txt_CT_Q.Invoke((MethodInvoker)delegate () { Txt_CT_Q.Text = ctqT; });

                                            ctmT = tempDevice.PlcModbus.master.ReadHoldingRegisters(1, ushort.Parse(tempDevice.CT_M.Substring(1)), 1)[0].ToString();
                                            Txt_CT_M.Invoke((MethodInvoker)delegate () { Txt_CT_M.Text = ctmT; });


                                            uiLabel23.Invoke((MethodInvoker)delegate ()
                                            {
                                                uiLabel23.BackColor = Color.Green;
                                                uiLabel23.Text = "数据读取成功";
                                            });



                                        }


                                        if (statuT == "1")
                                        {
                                            if (tempDevice.TbsState != 2)
                                                tempDevice.TbsState = 1;
                                        }
                                        else
                                        {
                                            tempDevice.TbsState = 0;
                                            tempDevice.TbsCount = 0;
                                        }


                                        uiLabel29.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiLabel29.Text = "state " + tempDevice.TbsState + "-" + tempDevice.TbsCount;
                                        });



                                        tempDevice.IsError = false;
                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(2, "读取PLC数据完成") + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                    }
                                    catch (Exception ex)
                                    {
                                        uiLabel23.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiLabel23.BackColor = Color.Red;
                                            uiLabel23.Text = "数据读取异常";
                                        });
                                        tempDevice.IsConnected = false;
                                        tempDevice.IsError = true;
                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());

                                        try
                                        {
                                            if (File.Exists(tempDevice.LogPath))
                                            {
                                                using (StreamWriter file = new StreamWriter(tempDevice.LogPath, true))
                                                {
                                                    file.WriteLine(tempDevice.LogStr);
                                                }
                                            }                                        
                                        }
                                        catch { }

                                        continue;
                                    }


                                    try
                                    {
                                        if (tempDevice.InterfaceID != null)
                                        {
                                            tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(2, "开始POST数据") + new StackTrace(true).GetFrame(0).GetFileLineNumber());

                                            if (tempDevice.InterfaceID.Contains(','))
                                            {
                                                string[] tempArray = tempDevice.InterfaceID.Split(',');
                                                string pqmBack = string.Empty;
                                                JsonData jdTempTotal = new JsonData(ctmT, ctqT);
                                                jdTempTotal.interfaceID = tempDevice.InterfaceID;
                                                for (int i = 0; i < tempArray.Length; i++)
                                                {
                                                    try
                                                    {
                                                        JsonData jd = new JsonData(ctmT, ctqT);
                                                        jd.interfaceID = tempArray[i];



                                                        if (tempDevice.TbsState == 0 || tempDevice.TbsState == 2)
                                                        {
                                                            int tempStatus = 0;
                                                            if (int.TryParse(statuT, out tempStatus))
                                                            {
                                                                jd.status = tempStatus;

                                                                if (i == 0)
                                                                { jdTempTotal.status = tempStatus; }
                                                            }

                                                            jd.statusCode = statusCodeT;
                                                            if (i == 0)
                                                            { jdTempTotal.statusCode = statusCodeT; }
                                                        }
                                                        else
                                                        {
                                                            jd.status = 0;
                                                            if (i == 0)
                                                            { jdTempTotal.status = 0; }

                                                            jd.statusCode = "0";
                                                            if (i == 0)
                                                            { jdTempTotal.statusCode = "0"; }
                                                        }

                                                      

                                                        int tempPass = 0;
                                                        if (int.TryParse(passT, out tempPass))
                                                        {
                                                            jd.passQty = tempPass;
                                                            if (i == 0)
                                                            { jdTempTotal.passQty = tempPass; }
                                                        }

                                                        int tempFail = 0;
                                                        if (int.TryParse(failT, out tempFail))
                                                        {
                                                            jd.failQty = tempFail;
                                                            if (i == 0)
                                                            { jdTempTotal.failQty = tempFail; }
                                                        }

                                                        int tempErrorcnt = 0;
                                                        if (int.TryParse(errorCntT, out tempErrorcnt))
                                                        {
                                                            jd.errorCnt = tempErrorcnt;
                                                            if (i == 0)
                                                            { jdTempTotal.errorCnt = tempErrorcnt; }
                                                        }

                                                        double tempErrorT = 0;
                                                        if (double.TryParse(errorTimeT, out tempErrorT))
                                                        {
                                                            jd.errorTimes = tempErrorT;
                                                            if (i == 0)
                                                            { jdTempTotal.errorTimes = tempErrorT; }
                                                        }

                                                        double tempCycle = 0;
                                                        if (double.TryParse(cycleTimeT, out tempCycle))
                                                        {
                                                            jd.cycleTime = tempCycle;
                                                            if (i == 0)
                                                            { jdTempTotal.cycleTime = tempCycle; }
                                                        }

                                                        double tempRun = 0;
                                                        if (double.TryParse(runningTimeT, out tempRun))
                                                        {
                                                            jd.runningTime = tempRun;
                                                            if (i == 0)
                                                            { jdTempTotal.runningTime = tempRun; }
                                                        }

                                                        double tempWait = 0;
                                                        if (double.TryParse(waitingTimeT, out tempWait))
                                                        {
                                                            jd.waitingTime = tempWait;
                                                            if (i == 0)
                                                            { jdTempTotal.waitingTime = tempWait; }
                                                        }


                                                        int tempSelf = 0;
                                                        if (int.TryParse(selfCheckT, out tempSelf))
                                                        {
                                                            jd.selfCheck = tempSelf;
                                                            if (i == 0)
                                                            { jdTempTotal.selfCheck = tempSelf; }
                                                        }

                                                        int tempInput = 0;
                                                        if (int.TryParse(inputQtyT, out tempInput))
                                                        {
                                                            jd.inputQty = tempInput;
                                                            if (i == 0)
                                                            { jdTempTotal.inputQty = tempInput; }
                                                        }



                                                        jd.barcode = barcodeT;

                                                        jd.model = modelT;

                                                        if (i == 0)
                                                        {
                                                            jdTempTotal.barcode = barcodeT;

                                                            jdTempTotal.model = modelT;
                                                        }

                                                        string jsonDataTemp = Json.Serialize(jd);

                                                        string jsonData = "[" + jsonDataTemp + "]";

                                                        try
                                                        {
                                                            string backPqmData = PublicClass.Post(Form1.PQMserverURL, jsonData);


                                                            if (backPqmData.Contains("201") || backPqmData.Contains(""))
                                                            {
                                                                pqmBack += i + 1 + "上傳成功" + "-";
                                                            }
                                                            else if (backPqmData.Contains("400"))
                                                            {
                                                                pqmBack += i + 1 + "请求数据无效" + "-";
                                                            }
                                                            else if (backPqmData.Contains("404"))
                                                            {
                                                                pqmBack += i + 1 + "指定的信號不存在" + "-";
                                                            }
                                                            else if (backPqmData.Contains("500"))
                                                            {
                                                                pqmBack += i + 1 + "內部發生錯誤" + "-";
                                                            }
                                                            else
                                                            {
                                                                pqmBack += i + 1 + "其他未知錯誤" + "-";
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            pqmBack += i + 1 + "POST数据异常" + "-";
                                                            tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                                        }



                                                   


                                                        Thread.Sleep(1);

                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                                    }

                                                    try
                                                    {
                                                        string jsonDataTempTotal = Json.Serialize(jdTempTotal);
                                                        string jsonDataTotal = "[" + jsonDataTempTotal + "]";
                                                        string jsonDataTempTotal1 = jsonDataTotal.Replace(",", "\r\n");
                                                        uiRichTextBox1.Invoke((MethodInvoker)delegate () { uiRichTextBox1.Text = jsonDataTempTotal1 + "\r\n" + DateTime.Now.ToString(); });
                                                        uiTextBox2.Invoke((MethodInvoker)delegate () { uiTextBox2.Text = pqmBack; });
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    JsonData jd = new JsonData(ctmT, ctqT);
                                                    jd.interfaceID = tempDevice.InterfaceID;

                                                    if (tempDevice.TbsState == 0 || tempDevice.TbsState == 2)
                                                    {
                                                        int tempStatus = 0;
                                                        if (int.TryParse(statuT, out tempStatus))
                                                        {
                                                            jd.status = tempStatus;
                                                        }

                                                        jd.statusCode = statusCodeT;
                                                    }
                                                    else
                                                    {
                                                        jd.status = 0;


                                                        jd.statusCode = "0";
                                                    }

                                                    int tempPass = 0;
                                                    if (int.TryParse(passT, out tempPass))
                                                    {
                                                        jd.passQty = tempPass;
                                                    }

                                                    int tempFail = 0;
                                                    if (int.TryParse(failT, out tempFail))
                                                    {
                                                        jd.failQty = tempFail;
                                                    }

                                                    int tempErrorcnt = 0;
                                                    if (int.TryParse(errorCntT, out tempErrorcnt))
                                                    {
                                                        jd.errorCnt = tempErrorcnt;
                                                    }

                                                    double tempErrorT = 0;
                                                    if (double.TryParse(errorTimeT, out tempErrorT))
                                                    {
                                                        jd.errorTimes = tempErrorT;
                                                    }

                                                    double tempCycle = 0;
                                                    if (double.TryParse(cycleTimeT, out tempCycle))
                                                    {
                                                        jd.cycleTime = tempCycle;
                                                    }

                                                    double tempRun = 0;
                                                    if (double.TryParse(runningTimeT, out tempRun))
                                                    {
                                                        jd.runningTime = tempRun;
                                                    }

                                                    double tempWait = 0;
                                                    if (double.TryParse(waitingTimeT, out tempWait))
                                                    {
                                                        jd.waitingTime = tempWait;
                                                    }


                                                    int tempSelf = 0;
                                                    if (int.TryParse(selfCheckT, out tempSelf))
                                                    {
                                                        jd.selfCheck = tempSelf;
                                                    }

                                                    int tempInput = 0;
                                                    if (int.TryParse(inputQtyT, out tempInput))
                                                    {
                                                        jd.inputQty = tempInput;
                                                    }

                                                    jd.barcode = barcodeT;

                                                    jd.model = modelT;

                                                    string jsonDataTemp = Json.Serialize(jd);

                                                    string jsonData = "[" + jsonDataTemp + "]";

                                                    string jsonDataTemp2 = jsonData.Replace(",", "\r\n");

                                                    try
                                                    {
                                                        string backPqmData = PublicClass.Post(Form1.PQMserverURL, jsonData);

                                                        if (backPqmData.Contains("201") || backPqmData.Contains(""))
                                                        {
                                                            uiTextBox2.Invoke((MethodInvoker)delegate () { uiTextBox2.Text = "上傳成功"; });
                                                        }
                                                        else if (backPqmData.Contains("400"))
                                                        {
                                                            uiTextBox2.Invoke((MethodInvoker)delegate () { uiTextBox2.Text = "请求数据无效"; });
                                                        }
                                                        else if (backPqmData.Contains("404"))
                                                        {
                                                            uiTextBox2.Invoke((MethodInvoker)delegate () { uiTextBox2.Text = "指定的信號不存在"; });
                                                        }
                                                        else if (backPqmData.Contains("500"))
                                                        {
                                                            uiTextBox2.Invoke((MethodInvoker)delegate () { uiTextBox2.Text = "內部發生錯誤"; });
                                                        }
                                                        else
                                                        {
                                                            uiTextBox2.Invoke((MethodInvoker)delegate () { uiTextBox2.Text = "其他未知錯誤"; });
                                                        }

                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        uiTextBox2.Invoke((MethodInvoker)delegate () { uiTextBox2.Text = "POST数据异常"; });
                                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                                    }

                                                  

                                                    uiRichTextBox1.Invoke((MethodInvoker)delegate () { uiRichTextBox1.Text = jsonDataTemp2 + "\r\n" + DateTime.Now.ToString(); });

                                                }
                                                catch (Exception ex)
                                                {
                                                    tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                                }
                                            }

                                            if (tempDevice.IsTimeEnable)
                                            {
                                                if (DateTime.Now <= Convert.ToDateTime(Form1.EndTime) && DateTime.Now >= Convert.ToDateTime(Form1.StartTime))
                                                {
                                                    tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(2, "启动定时POST") + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                                    try
                                                    {
                                                        for (int i = 0; i < Form1.MachineList.Count; i++)
                                                        {
                                                            if (Form1.MachineList[i].MachineName == tempDevice.VirtualMachine)
                                                            {
                                                                for (int j = 0; j < Form1.MachineList[i].MachineIdList.Count; j++)
                                                                {
                                                                    JsonData jd = new JsonData(ctmT, ctqT);
                                                                    jd.interfaceID = Form1.MachineList[i].MachineIdList[j];

                                                                    int tempStatus = 0;
                                                                    if (int.TryParse(statuT, out tempStatus))
                                                                    {
                                                                        jd.status = tempStatus;
                                                                    }

                                                                    jd.statusCode = statusCodeT;

                                                                    int tempPass = 0;
                                                                    if (int.TryParse(passT, out tempPass))
                                                                    {
                                                                        jd.passQty = tempPass + j;
                                                                    }

                                                                    int tempFail = 0;
                                                                    if (int.TryParse(failT, out tempFail))
                                                                    {
                                                                        jd.failQty = tempFail;
                                                                    }

                                                                    int tempErrorcnt = 0;
                                                                    if (int.TryParse(errorCntT, out tempErrorcnt))
                                                                    {
                                                                        jd.errorCnt = tempErrorcnt;
                                                                    }

                                                                    double tempErrorT = 0;
                                                                    if (double.TryParse(errorTimeT, out tempErrorT))
                                                                    {
                                                                        jd.errorTimes = tempErrorT;
                                                                    }

                                                                    double tempCycle = 0;
                                                                    if (double.TryParse(cycleTimeT, out tempCycle))
                                                                    {
                                                                        jd.cycleTime = tempCycle + i / 10;
                                                                    }

                                                                    double tempRun = 0;
                                                                    if (double.TryParse(runningTimeT, out tempRun))
                                                                    {
                                                                        jd.runningTime = tempRun;
                                                                    }

                                                                    double tempWait = 0;
                                                                    if (double.TryParse(waitingTimeT, out tempWait))
                                                                    {
                                                                        jd.waitingTime = tempWait;
                                                                    }


                                                                    int tempSelf = 0;
                                                                    if (int.TryParse(selfCheckT, out tempSelf))
                                                                    {
                                                                        jd.selfCheck = tempSelf;
                                                                    }

                                                                    int tempInput = 0;
                                                                    if (int.TryParse(inputQtyT, out tempInput))
                                                                    {
                                                                        jd.inputQty = tempInput + j;
                                                                    }

                                                                    jd.barcode = barcodeT;

                                                                    jd.model = modelT;

                                                                    string jsonDataTemp = Json.Serialize(jd);

                                                                    string jsonData = "[" + jsonDataTemp + "]";

                                                                    //string jsonDataTemp2 = jsonData.Replace(",", "\r\n");


                                                                    try
                                                                    {
                                                                        string backPqmData = PublicClass.Post(Form1.PQMserverURL, jsonData);
                                                                    }
                                                                    catch (Exception ex)
                                                                    {

                                                                    }
                                                                }

                                                                break;
                                                            }
                                                        }
                                                    }
                                                    catch
                                                    { }
                                                }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    for (int i = 0; i < Form1.MachineList.Count; i++)
                                                    {
                                                        if (Form1.MachineList[i].MachineName == tempDevice.VirtualMachine)
                                                        {
                                                            for (int j = 0; j < Form1.MachineList[i].MachineIdList.Count; j++)
                                                            {
                                                                JsonData jd = new JsonData(ctmT, ctqT);
                                                                jd.interfaceID = Form1.MachineList[i].MachineIdList[j];

                                                                int tempStatus = 0;
                                                                if (int.TryParse(statuT, out tempStatus))
                                                                {
                                                                    jd.status = tempStatus;
                                                                }

                                                                jd.statusCode = statusCodeT;

                                                                int tempPass = 0;
                                                                if (int.TryParse(passT, out tempPass))
                                                                {
                                                                    jd.passQty = tempPass + j;
                                                                }

                                                                int tempFail = 0;
                                                                if (int.TryParse(failT, out tempFail))
                                                                {
                                                                    jd.failQty = tempFail;
                                                                }

                                                                int tempErrorcnt = 0;
                                                                if (int.TryParse(errorCntT, out tempErrorcnt))
                                                                {
                                                                    jd.errorCnt = tempErrorcnt;
                                                                }

                                                                double tempErrorT = 0;
                                                                if (double.TryParse(errorTimeT, out tempErrorT))
                                                                {
                                                                    jd.errorTimes = tempErrorT;
                                                                }

                                                                double tempCycle = 0;
                                                                if (double.TryParse(cycleTimeT, out tempCycle))
                                                                {
                                                                    jd.cycleTime = tempCycle + i / 10;
                                                                }

                                                                double tempRun = 0;
                                                                if (double.TryParse(runningTimeT, out tempRun))
                                                                {
                                                                    jd.runningTime = tempRun;
                                                                }

                                                                double tempWait = 0;
                                                                if (double.TryParse(waitingTimeT, out tempWait))
                                                                {
                                                                    jd.waitingTime = tempWait;
                                                                }


                                                                int tempSelf = 0;
                                                                if (int.TryParse(selfCheckT, out tempSelf))
                                                                {
                                                                    jd.selfCheck = tempSelf;
                                                                }

                                                                int tempInput = 0;
                                                                if (int.TryParse(inputQtyT, out tempInput))
                                                                {
                                                                    jd.inputQty = tempInput + j;
                                                                }

                                                                jd.barcode = barcodeT;

                                                                jd.model = modelT;

                                                                string jsonDataTemp = Json.Serialize(jd);

                                                                string jsonData = "[" + jsonDataTemp + "]";

                                                                //string jsonDataTemp2 = jsonData.Replace(",", "\r\n");


                                                                try
                                                                {
                                                                    string backPqmData = PublicClass.Post(Form1.PQMserverURL, jsonData);
                                                                }
                                                                catch (Exception ex)
                                                                {

                                                                }
                                                            }

                                                            break;
                                                        }
                                                    }
                                                }
                                                catch
                                                { }
                                            }
                                            //模擬
                                          

                                            tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(2, "POST数据完成") + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                    }



                                }
                                else
                                {
                                    try
                                    {
                                        if (tempDevice.PlcModbus.tcpClient != null && tempDevice.PlcModbus.tcpClient.Connected)
                                        {
                                            tempDevice.PlcModbus.tcpClient.GetStream().Close();
                                            tempDevice.PlcModbus.tcpClient.Close();
                                            tempDevice.PlcModbus.tcpClient.Dispose();
                                        }

                                        tempDevice.PlcModbus.tcpClient = new TcpClient(tempDevice.Ip, 502);
                                        tempDevice.PlcModbus.master = ModbusIpMaster.CreateIp(tempDevice.PlcModbus.tcpClient);
                                        tempDevice.PlcModbus.master.Transport.Retries = 0;//不重试
                                        tempDevice.PlcModbus.master.Transport.ReadTimeout = 100;//读取超时100ms
                                        tempDevice.IsConnected = true;

                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(2, "连接设备成功") + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                    }
                                    catch (Exception ex)
                                    {
                                        uiLabel23.Invoke((MethodInvoker)delegate ()
                                        {
                                            uiLabel23.BackColor = Color.Red;
                                            uiLabel23.Text = "设备连接异常";
                                        });
                                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                    }

                                    try
                                    {
                                        if (File.Exists(tempDevice.LogPath))
                                        {
                                            using (StreamWriter file = new StreamWriter(tempDevice.LogPath, true))
                                            {
                                                file.WriteLine(tempDevice.LogStr);
                                            }
                                        }
                                    }
                                    catch { }

                                    continue;
                                }
                            }
                            else
                            {
                                try
                                {
                                    uiLabel23.Invoke((MethodInvoker)delegate ()
                                    {
                                        uiLabel23.BackColor = Color.Red;
                                        uiLabel23.Text = "设备连接异常";
                                    });

                                    if (tempDevice.PlcModbus.tcpClient != null && tempDevice.PlcModbus.tcpClient.Connected)
                                    {
                                        tempDevice.PlcModbus.tcpClient.GetStream().Close();
                                        tempDevice.PlcModbus.tcpClient.Close();
                                        tempDevice.PlcModbus.tcpClient.Dispose();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                                }
                                finally
                                {
                                    tempDevice.IsConnected = false;
                                }

                                try
                                {
                                    if (File.Exists(tempDevice.LogPath))
                                    {
                                        using (StreamWriter file = new StreamWriter(tempDevice.LogPath, true))
                                        {
                                            file.WriteLine(tempDevice.LogStr);
                                        }
                                    }
                                }
                                catch { }

                                continue;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(1, ex.ToString()) + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                    }
                  
                    try
                    {
                        tempDevice.LogStr.Append("\r\n" + PublicClass.NetLog(0, "结束") + new StackTrace(true).GetFrame(0).GetFileLineNumber());
                        if (File.Exists(tempDevice.LogPath))
                        {
                            using (StreamWriter file = new StreamWriter(tempDevice.LogPath, true))
                            {
                                file.WriteLine(tempDevice.LogStr);
                            }
                        }
                    }
                    catch { }
                }
                Form1.Delay(Form1.UpTime - 400);             
            }
        }

 
    }
}
